#!/bin/bash

# config
PUBLISHER_ADDR="http://${PUBLISHER_HOST}:${PUBLISHER_PORT}/code-sign"

POST_FILE_MD5="file_md5"
POST_KEY_NAME="key_name"
POST_KEY_TYPE="key_type"
POST_FILE_TYPE="file_type"
POST_JOB_ID="job_id"
POST_OS_ORIJECT="os_project"
POST_SIGN_TYPE="sign_type"

KEY_NAME_VALUE=""
KEY_TYPE_VALUE=""
FLIE_TYPE_VALUE=""
SIGN_TYPE_VALUE=""


REQ_ENCODED_FILE_CONTENT="encoded_file_content"
REQ_FILE_MD5="file_md5"

JOB_YAML="/lkp/scheduled/job.yaml"
YAML_ID="id"
YAML_OS_PROJECT="os_project"

ID_VALUE=""
OS_PROJECT_VALUE=""

if [ $# -ne 2 ]
then
	echo "the number of input parameters is error"
	exit 1
fi

if [ -z "$PUBLISHER_HOST" ] || [ -z "$PUBLISHER_PORT" ]
then
	echo "publisher addr error"
	exit 1
fi

echo "test input param2 : $2"
if [ "$2" == "--ima-digestlist" ]
then
	KEY_NAME_VALUE="last-koee"
	KEY_TYPE_VALUE="x509"
	FILE_TYPE_VALUE="kernel-module"
	SIGN_TYPE_VALUE="cms"
elif [ "$2" == "--module" ]
then
	KEY_NAME_VALUE=""
	KEY_TYPE_VALUE="x509"
	FILE_TYPE_VALUE="kernel-module"
	SIGN_TYPE_VALUE="cms"
elif [ "$2" == "--efi" ]
then
	KEY_NAME_VALUE="default-x509ee"
	KEY_TYPE_VALUE="x509ee"
	FILE_TYPE_VALUE="efi-image"
	SIGN_TYPE_VALUE="authenticode"
else
	echo "input type is error, supported types are: --ima-digeslist, --module, --efi"
	exit 1
fi

ID_VAULE="$(grep -rwn 'id\:' $JOB_YAML | awk '{print $2}')"
OS_PROJECT_VALUE="$(grep -rwn 'os_project\:' $JOB_YAML | awk '{print $2}')"

# function definition
get_json_value(){
	echo "$1" | awk -F "[{,:}]" '{for(i=1;i<NF;i++){if($i~"'$2'"){print $(i+1)}}}' | sed 's/\"//g'
}

file="$1"
file_md5="$(md5sum $file | awk '{printf $1}')"
json="{\"$POST_FILE_MD5\":\"$file_md5\", \"$POST_KEY_NAME\":\"$KEY_NAME_VALUE\", \"$POST_KEY_TYPE\":\"$KEY_TYPE_VALUE\", \
\"$POST_FILE_TYPE\":\"$FILE_TYPE_VALUE\", \"$POST_JOB_ID\":\"$ID_VAULE\", \"$POST_OS_ORIJECT\":\"$OS_PROJECT_VALUE\", \"$POST_SIGN_TYPE\":\"$SIGN_TYPE_VALUE\"}"


curl_file="$file"
if [ "$2" == "--ima-digestlist" ]
then
	curl_file="$file.ko"
	cp "$file" "$curl_file"
fi

req="$(curl "$PUBLISHER_ADDR" \
	    -F "file=@$curl_file" \
	    -F "data=$json;type=application/json")"
[ $? -eq 0 ] || { echo "Fail to post sign service, REQ="; echo "req"; exit 1; }
echo "$req" > req.out


encoded_file_content=$(get_json_value "$req" "$REQ_ENCODED_FILE_CONTENT")
[ $? -eq 0 ] || { echo "Fail to parser $REQ_ENCODED_FILE_CONTENT"; exit 1; }
echo -e "$encoded_file_content" | base64 -d > $file.sig
[ $? -eq 0 ] || { echo "Fail to decode value of $encoded_file_content"; exit 1; }

file_md5=$(get_json_value "$req" "$REQ_FILE_MD5")
[ $? -eq 0 ] || { echo "Fail to parser $REQ_FILE_MD5"; exit 1; }
md5sum $file.sig | grep "$flie_md5"
[ $? -eq 0 ] || { echo "Fail to check md5 of $file.sig"; exit 1; }

echo "Sign $file ok!"
exit 0
